//package me.zhengjie.timing;
//
//import lombok.RequiredArgsConstructor;
//import me.zhengjie.WcsReport.WcsReportService;
//import me.zhengjie.agvSend.AgvSendService;
//import me.zhengjie.pojo.dto.AgvTaskSubmitDto;
//import me.zhengjie.pojo.dto.InboundIsCodeExistDto;
//import me.zhengjie.pojo.dto.TargetRoute;
//import me.zhengjie.pojo.entity.WcsFluentFrameConfig;
//import me.zhengjie.pojo.entity.WcsInboundMission;
//import me.zhengjie.pojo.entity.WcsOutboundMission;
//import me.zhengjie.pojo.vo.EmptyContainer;
//import me.zhengjie.pojo.vo.ReturnVo;
//import me.zhengjie.sqlservice.WcsFluentFrameConfigService;
//import me.zhengjie.sqlservice.WcsInboundMissionService;
//import me.zhengjie.sqlservice.WcsOutboundMissionService;
//import me.zhengjie.tcp.FluentFrameTCPA;
//import me.zhengjie.tcp.FluentFrameTCPB;
//import me.zhengjie.util.state.MaterialStatus;
//import me.zhengjie.util.state.TaskStatus;
//import me.zhengjie.util.state.TaskType;
//import me.zhengjie.utility.IdWorker;
//import org.slf4j.Logger;
//import org.slf4j.LoggerFactory;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import java.time.LocalDateTime;
//import java.util.ArrayList;
//import java.util.List;
//
//@Component
//@RequiredArgsConstructor
//public class FluentFrameTiming {
//    private static final Logger fluentFrame = LoggerFactory.getLogger("fluentFrame");
//
//    private final WcsFluentFrameConfigService wcsFluentFrameConfigService;
//
//    private final FluentFrameTCPA fluentFrameTCPA;
//
//    private final FluentFrameTCPB fluentFrameTCPB;
//
//    private final WcsReportService wcsReportService;
//
//    private final WcsInboundMissionService wcsInboundMissionService;
//
//    private final AgvSendService agvSendService;
//
//    private final WcsOutboundMissionService wcsOutboundMissionService;
//
//    private final IdWorker idWorker;
//
//    @Transactional
//    @Scheduled(fixedDelay = 1000)
//    public void fluentFrame() {
//        List<WcsOutboundMission> wcsOutboundMissions = wcsOutboundMissionService.selectTask(TaskStatus.Task_create.getStatus(), TaskType.WORKBIN.getStatus());
//        for (WcsOutboundMission wcsOutboundMission : wcsOutboundMissions) {
//            //出库任务终点工位
//            String destination = wcsOutboundMission.getDestination();
//            //根据出库任务工位查询，查询对应流利架、
//            List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectStorageRegion(destination);
//            if (!wcsFluentFrameConfigList.isEmpty()) {
//                for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
//                    Integer outboundStorageSizeAddress = wcsFluentFrameConfig.getOutboundStorageSizeAddress();
//                    String storageRegion = wcsFluentFrameConfig.getStorageRegion();
//                    Integer unitId = wcsFluentFrameConfig.getUnit_id();
//                    Integer size = wcsFluentFrameConfig.getSize();
//                    Integer storageSize = 3;
//                    //查询流利架出库三个储位有货数量
////                    Integer outboundSize = fluentFrameTCPA.readHoldingRegisters(outboundStorageSizeAddress, unitId);
//                    storageSize = storageSize - size;
//                    //查询2楼料箱状态为0的入库任务到该储位
////                List<WcsInboundMission> wcsInboundMissionList = wcsInboundMissionService.selectStatusAndDestinationAndContainerTypePage(TaskStatus.Task_create, storageCode, TaskType.WORKBIN.getStatus(), storageSize);
//                    if (storageSize > 0) {
//                        List<WcsOutboundMission> wcsOutboundMissionList = wcsOutboundMissionService.selectStatusAndDestinationAndContainerTypePage(TaskStatus.Task_create, storageRegion, TaskType.WORKBIN.getStatus(), storageSize);
//                        if (!wcsOutboundMissionList.isEmpty()) {
//                            //下发agv任务，修改状态为1
//                            for (WcsOutboundMission outboundMission : wcsOutboundMissionList) {
//                                String outboundCode = outboundMission.getOutboundCode();
//                                Integer id = outboundMission.getId();
//                                AgvTaskSubmitDto agvTaskSubmitDto = new AgvTaskSubmitDto();
//                                //todo 任务类型，根据现场情况来定
//                                agvTaskSubmitDto.setTaskType("任务类型");
//                                ArrayList<TargetRoute> targetRouteList = new ArrayList<>();
//                                TargetRoute targetRoute = new TargetRoute();
//                                //添加起点
//                                targetRoute.setSeq(0);
//                                targetRoute.setType("SITE");
//                                targetRoute.setCode(outboundMission.getSource());
//                                targetRoute.setOperation(TaskType.TASK_PUT.getMessage());
//                                //添加终点
//                                targetRoute.setSeq(1);
//                                targetRoute.setType("SITE");
//                                targetRoute.setCode(storageRegion);
//                                targetRoute.setOperation(TaskType.TASK_COMPLETE.getMessage());
//                                targetRouteList.add(targetRoute);
//                                agvTaskSubmitDto.setTargetRoute(targetRouteList);
//                                String deliveryCode = String.valueOf(outboundCode);
//                                agvTaskSubmitDto.setRobotTaskCode(deliveryCode);
//                                agvTaskSubmitDto.setInitPriority(outboundMission.getPriority());
//                                String taskCode = agvSendService.agvTaskSubmit(agvTaskSubmitDto);
//                                if (taskCode != null) {
//                                    size++;
//                                    //修改流利架数量
//                                    wcsFluentFrameConfigService.updateSize(id, size);
//                                    //修改任务状态已发送
//                                    boolean b = wcsInboundMissionService.updateMissionStatus(outboundCode, TaskStatus.task_send.getStatus());
//                                    if (!b) {
//                                        fluentFrame.error("出库下发任务，修改数据库失败");
//                                        throw new RuntimeException("出库下发任务，修改数据库失败");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        //查询所有流利架
//        List<WcsFluentFrameConfig> wcsFluentFrameConfigList = wcsFluentFrameConfigService.selectAll();
//        if (!wcsFluentFrameConfigList.isEmpty()) {
//            for (WcsFluentFrameConfig wcsFluentFrameConfig : wcsFluentFrameConfigList) {
//                Integer singleOrDouble = wcsFluentFrameConfig.getSingleOrDouble();
//                Integer size = wcsFluentFrameConfig.getSize();
//                if (singleOrDouble == 1) {
//                    //单层流利架
//                    Integer storageSize = 4;
//                    storageSize = storageSize -size;
//                    if (storageSize >= 2){
//                        //单层流利架有二个储位时需要补空箱
//                        for (Integer i = 0; i < storageSize; i++) {
//                            //发送空箱终点储位申请
//                            String storageRegion = wcsFluentFrameConfig.getStorageRegion();
//                            String storageCode = wcsFluentFrameConfig.getStorageCode();
//                            ReturnVo returnVo = wcsReportService.emptyContainer(storageRegion);
//                            if (returnVo.getCode() == 200){
//                                EmptyContainer emptyContainer = (EmptyContainer)returnVo.getData();
//                                String outboundCode = String.valueOf(idWorker.nextId());
//                                //todo 生成出空箱任务，发给AGV
//                                if (true){
//                                    //生成出库任务
//                                    WcsOutboundMission wcsOutboundMission = new WcsOutboundMission();
//                                    wcsOutboundMission.setOutboundCode("out"+outboundCode);
//                                    wcsOutboundMission.setMissionStatus(TaskStatus.task_send.getStatus());
//                                    wcsOutboundMission.setContainerCode(emptyContainer.getContainerCode());
//                                    wcsOutboundMission.setSource(emptyContainer.getStorageCode());
//                                    wcsOutboundMission.setDestination(storageCode);
//                                    wcsOutboundMission.setCreateTime(LocalDateTime.now());
//                                    wcsOutboundMission.setUpdateTime(LocalDateTime.now());
//                                    wcsOutboundMission.setContainerType(TaskType.WORKBIN.getStatus());
//                                    wcsOutboundMission.setPriority(90);
//                                    boolean b = wcsOutboundMissionService.insertOutbound(wcsOutboundMission);
//                                    if (!b) {
//                                        fluentFrame.error("数据库异常，添加出库任务失败");
//                                        throw new RuntimeException("数据库异常，添加出库任务失败");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                } else if (singleOrDouble == 2) {
//                    //双层流利架
//                    //查询气缸地址位，当前状态
//                    Integer id = wcsFluentFrameConfig.getId();
//                    Integer cylinder = wcsFluentFrameConfig.getCylinder();
//                    String region = wcsFluentFrameConfig.getRegion();
//                    Integer unitId = wcsFluentFrameConfig.getUnit_id();
//                    Integer sortingAddress = wcsFluentFrameConfig.getSortingAddress();
//                    Integer sortingResultAddress = wcsFluentFrameConfig.getSortingResultAddress();
//                    Integer mode = wcsFluentFrameConfig.getMode();
//                    //判断当前是A区还是B区
//                    if (TaskType.FLUENT_FRAME_A.getMessage().equals(region)) {
//                        Integer cylinderStatus = fluentFrameTCPA.readHoldingRegisters(cylinder, unitId);
//                        //判断气缸当前状态,入库
//                        if (cylinderStatus == 2) {
//                            Integer sortingStatus = fluentFrameTCPA.readHoldingRegisters(sortingAddress, unitId);
//                            if (sortingStatus == 1) {
//                                //分拣区有货，获取读码结果
//                                Integer sortingReadAddress = wcsFluentFrameConfig.getSortingReadAddress();
//                                String palletCode = fluentFrameTCPA.readHoldingRegistersString(sortingReadAddress, unitId);
//                                //是空箱入库还是正常入库
//                                if (mode == 0) {
//                                    //空箱入库
//                                    //todo 中间表嵌套信息不能有物料  向WMS下发空箱入库申请储位
//
//                                } else if (mode == 1) {
//                                    // 向WMS发送容器是否已入库
//                                    InboundIsCodeExistDto inboundIsCodeExistDto = new InboundIsCodeExistDto();
//                                    inboundIsCodeExistDto.setContainerCode(palletCode);
//                                    inboundIsCodeExistDto.setNest(false);
//                                    boolean b = wcsReportService.inboundIsCodeExist(inboundIsCodeExistDto);
//                                    if (!b) {
//                                        //todo 中间表查询嵌套信息 并向WMS获取信息，进行库存对比(1查询是否嵌套，2容器编码是否已存在库区，3原物料Q是否自检合格)
//                                        if (true) {
//                                            //当前料箱无误，向PLC发送分拣位无误
//                                            //记录分拣区流利架容器编码
//                                            wcsFluentFrameConfigService.updateSortingContainerCode(id, palletCode);
//                                            fluentFrameTCPA.writeWithRetry(sortingResultAddress, 1, unitId, MaterialStatus.RETRY_COUNT.getStatus());
//                                            //todo下发agv任务，起点终点(起点不一定有货，是否需要通知agv取货) 向wms申请终点储位入库
//                                        }
//                                    } else {
//                                        //库存中存在相同栈板。写入PLC
//                                        fluentFrameTCPA.writeWithRetry(sortingResultAddress, 3, unitId, MaterialStatus.RETRY_COUNT.getStatus());
//                                    }
//                                }
//                            }
//                        }
//                    } else if (TaskType.FLUENT_FRAME_B.getMessage().equals(region)) {
//                        //todo B从A复制过来就行
//                    }
//                }
//            }
//        }
//    }
//}
